package com.cfh.personprovider.controller;

import com.cfh.domain.Person;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class PersonProviderController {

    private static final Random random = new Random();

    private final Map<Long, Person> personMap = new ConcurrentHashMap<>();

    @PostMapping("/person/save")
    public boolean savePerson(@RequestBody Person person) {
        return personMap.put(person.getId(), person) == null;
    }

    @GetMapping("/person/findAll")
    @HystrixCommand(
            fallbackMethod = "fallbackForFindAllPersons",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
                            value = "100")
            })
    public Collection<Person> findAll() throws Exception {
        int value = random.nextInt(200);

        Thread.sleep(value);

        System.out.println("mothod cost " + value + "ms");

        return personMap.values();
    }


    /**
     * {@link #findAll()} Fallback方法
     *
     * @return 返回空集合
     */
    public Collection<Person> fallbackForFindAllPersons() {
        System.err.println("fallbackForFindAllPersons is invoked！");
        return Collections.emptyList();
    }
}
